﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;

namespace ebMS3dotnet.Core
{
    class ebMS3PackagingRequestChannel:ebMS3PackagingChannelBase<IRequestChannel>, IRequestChannel
    {
        internal ebMS3PackagingRequestChannel(ChannelManagerBase channelManager,
            IRequestChannel innerChannel)
            : base(channelManager, innerChannel) { }

        public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
        {
            WriteUserMessageHeader(message);
            return InnerChannel.BeginRequest(message, timeout, callback, state);
        }

        private void WriteUserMessageHeader(Message message)
        {
            ebMS3ClientParameters clientParameters = GetProperty<ChannelParameterCollection>()
                .OfType<ebMS3ClientParameters>()
                .Single();

            IebMS3HeaderWriter writer = new ebMS3UserMessageWriter(clientParameters);
            ebMS3Header header = new ebMS3Header(writer);

            message.Headers.Add(header);
        }

        public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
        {
            WriteUserMessageHeader(message);
            return InnerChannel.BeginRequest(message, callback, state);
        }

        public Message EndRequest(IAsyncResult result)
        {
            return InnerChannel.EndRequest(result);
        }

        public System.ServiceModel.EndpointAddress RemoteAddress
        {
            get { return InnerChannel.RemoteAddress; }
        }

        public Message Request(Message message, TimeSpan timeout)
        {
            WriteUserMessageHeader(message);
            return InnerChannel.Request(message, timeout);

        }

        public Message Request(Message message)
        {
            WriteUserMessageHeader(message);
            return InnerChannel.Request(message);
        }

        public Uri Via
        {
            get { return InnerChannel.Via; }
        }
    }
}
